# -*- coding: utf-8 -*-
# Created by liangfuting on 2020/8/18
# Copyright (c) 2020 liangfuting. All rights reserved.
from django.contrib.auth.hashers import make_password
from django.core.exceptions import ValidationError
from django import forms
from django.shortcuts import render, get_object_or_404, redirect
from django.urls import path
from django.utils.safestring import mark_safe
from web.models import UserInfo
from stark.service.v1 import StarkHandler,get_choice_text,SearchOption,BootStrapModelForm,StarkForm


class UserInfoAddModelForm(BootStrapModelForm):
    confirm_password = forms.CharField(label='确认密码', max_length=256, required=True)
    # confirm_password.widget=forms.PasswordInput()

    class Meta:
        model=UserInfo
        fields=['name','password','confirm_password','email','nick_name','phone','gender','roles','depart']

    def __init__(self,*args,**kwargs):
        super(UserInfoAddModelForm,self).__init__(*args,**kwargs)
        self.fields.get('password').widget=forms.PasswordInput()
        self.fields.get('confirm_password').widget=forms.PasswordInput()
        for name,field in self.fields.items():
            field.widget.attrs['class']='form-control'
            field.widget.attrs['placeholder']=field.label

    def clean_confirm_password(self):
        #钩子方法
        password=self.cleaned_data['password']
        confirm_password=self.cleaned_data['confirm_password']
        #密码不一致抛出异常
        # make_password

        if password != confirm_password:
            # print(password, confirm_password)
            raise ValidationError("两次输入密码不一致")
        # 密码一样的话，返回确认后的密码
        return confirm_password

    def clean(self):
        password=self.cleaned_data['password']
        #生成加密的密码
        hash_passwd=make_password(password)
        # print("password:",hash_passwd)
        self.cleaned_data['password']=hash_passwd
        #调用父类的保存方法，进行保存
        return self.cleaned_data


class UserInfoChangeModelForm(BootStrapModelForm):
    class Meta:
        model=UserInfo
        fields=['name','email','nick_name','phone','gender','roles','depart']

class ResetPasswordForm(StarkForm):
    password = forms.CharField(label='密码', max_length=256, required=True)
    confirm_password = forms.CharField(label='确认密码', max_length=256, required=True)
    password.widget = forms.PasswordInput()
    confirm_password.widget = forms.PasswordInput()

    def clean_confirm_password(self):
        #钩子方法
        password=self.cleaned_data['password']
        confirm_password=self.cleaned_data['confirm_password']
        #密码不一致抛出异常
        # make_password

        if password != confirm_password:
            # print(password, confirm_password)
            raise ValidationError("两次输入密码不一致")
        # 密码一样的话，返回确认后的密码
        return confirm_password



class UserInfoHandler(StarkHandler):

    def display_reset_pwd(self,obj=None,is_header=None):
        if is_header:
            return '重置密码'
        return mark_safe('<a href="{}">重置密码</a>'.format(self.reverse_reset_pwd_url(pk=obj.pk)))

    @property
    def get_reset_pwd_url_name(self):
        # print(self.get_url_name("reset_pwd"))
        return self.get_url_name("reset_pwd")

    def extra_urls(self):
        patterns = []
        patterns.append(path('reset/password/<int:pk>/', self.wapper(self.reset_pwd), name=self.get_reset_pwd_url_name))
        #stark/ web/userinfo/ reset/password/<int:pk>/ [name='web_userinfo_reset_pwd']
        # patterns.append(path('delete/<int:pk>/', self.wapper(self.delete_view), name=self.get_del_url_name))
        # print(self.extra_urls())
        # patterns.extend(self.extra_urls())
        # print(patterns)
        return patterns

    def reset_pwd(self,request,pk):
        form=ResetPasswordForm()
        if request.method =='POST':
            form=ResetPasswordForm(data=request.POST)
            if form.is_valid():
                #保存密码
                # print(form.cleaned_data)
                object=get_object_or_404(self.model_class,pk=pk)
                object.password=make_password(form.cleaned_data['password'])
                object.save()
                #返回之前的list页面
                return redirect(self.reverse_list_url())
            else:
                return render(request,'stark/change.html',{'form':form})

        context = {
            'form':form,
        }
        # return HttpResponse('reset password:{}'.format(pk))
        return render(request,'stark/change.html',context)

    def reverse_reset_pwd_url(self,*args,**kwargs):
        return self.reverse_common(self.get_reset_pwd_url_name, *args, **kwargs)


    # def get_reset_pwd_url_name(self):
    #     pass



    list_display = ['name','nick_name','email','phone',get_choice_text('性别','gender'),'depart',display_reset_pwd]
    search_list = ['name','nick_name','email','phone']
    search_group = [
        SearchOption(field='gender'),
        SearchOption(field='depart', db_condition={})
    ]
    #编辑和删除都会用这个modelform
    # model_form_class = UserInfoChangeModelForm

    def get_model_form_class(self,is_add=False):
        if is_add:
            return UserInfoAddModelForm
        return  UserInfoChangeModelForm

